package com.ruoyi.web.controller.common;

import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.course.service.RedisService;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/mail")
public class MailVerifyController {

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private RedisService redisService;

    @Value("${spring.mail.username}")
    private String from;

    /**
     * 发送邮件验证码并存储到 Redis
     * @param mail 发送的邮箱
     * @return
     */
    @PostMapping("/send")
    public AjaxResult sendEmailVerificationCode(@RequestParam String mail) {
        // 生成一个随机的6位验证码
        String verify = RandomStringUtils.randomNumeric(6);

        // 存储验证码到 Redis，设置过期时间为 10 分钟
        redisService.saveVerificationCode(mail, verify, 10);

        // 发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(mail);
        message.setSubject("测试服务平台-邮箱验证");
        message.setText("<h1>尊敬的用户您好：</h1><br>" +
                "<h5> 您正在进行邮箱验证，本次验证码为：<span style='color:#ec0808;font-size: 20px;'>" + verify + "</span>，请在10分钟内进行使用。</h5>" +
                "<h5>如非本人操作，请忽略此邮件，由此给您带来的不便请谅解！</h5> <h5 style='text-align: right;'>--测试服务平台</h5>");

        try {
            mailSender.send(message);
            return AjaxResult.success("验证码发送成功");
        } catch (Exception e) {
            return AjaxResult.error("验证码系统发送失败，请检查邮箱账号是否正确！");
        }
    }
}
